package org.csu.mypetstore.web.servlets;

import com.alibaba.fastjson.JSON;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.util.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class UsernameExistServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //！！加判错值？？用户那边给过来的是空值等，以前有过判断吧？
        String username = req.getParameter("username");
        AccountService accountService = new AccountService();
        Account result = accountService.getAccount(username);

        //区别
        //resp.setContentType("text/plain");
        resp.setContentType("text/json");//把下面转换的像json的字符串以json对象输出
        PrintWriter out = resp.getWriter();

        Result result1 = new Result();

        if(result == null){
            //注册用户名可用
            result1.setCode(0);
            result1.setMsg("Not Exist");
        }else{
            //注册用户名不可用
            result1.setCode(1);
            result1.setMsg("Exist");
        }

        String str = JSON.toJSONString(result1);//转换成符合json语法的字符串
        out.print(str);

        //养成好习惯，把流关闭
        out.flush();
        out.close();

    }
}
